<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/20/020
 * Time: 14:23
 */

namespace app\api\model;


use think\Exception;

class Category extends BaseModel {


    /**
     * 根据父级ID获取分类列表，并且可以通过 $noid 过滤掉某个分类和他的下级分类
     * @param int $pid
     * @param int $level
     * @param int $noid
     * @return array
     */
    public static function getCates($pid = 0, $level = 0, $noid = 0)
	{
		static $res = array();// static 定义函数内部的全局变量; 当函数内部调用该函数本身时，所得数据需要该定义才能追加保存到同一变量；
		$data = self::where([['pid', '=', $pid], ['id', 'neq', $noid]])->select();
		//print_r($data);die;
		foreach($data as $v)
		{
			$v['level'] = $level;	//记录级别
			$res[] = $v;
			//echo "<p>$v[catename]</p>";
			self::getCates($v['id'], $level+1, $noid);	//函数内部调用该函数本身
		}

        return $res;
    }

    /**
     * 创建或者编辑分类
     * @param $param
     * @param $id
     * @return array|\think\response\Json
     */
    public static function createOrUpdateCategory($param, $id) {

        try {
            if ($id > 0) {

                $category = self::get($id);
                if (!$category) {
                    return json(['code' => 1, 'msg' => '分类不存在']);
                }

                $check_name = self::where([['name', 'eq', $param['name']], ['id', 'neq', $id]])->find();
                if ($check_name) {
                    return ['code' => 1, 'msg' => '分类名称已存在!'];
                }

                $category->save($param);

            } else {
                $check_name = self::where([['name', 'eq', $param['name']]])->find();
                if ($check_name) {
                    return ['code' => 1, 'msg' => '分类名称已存在!'];
                }

                self::create($param);
            }
            return ['code' => 0, 'msg' => '保存成功'];
        } catch (Exception $e) {
            return ['code' => 1, 'msg' => $e->getMessage()];
        }
    }
}